/*
 * ProductDetailServlet.java
 * 作用：处理商品详情页的请求，根据商品ID获取并显示商品详细信息。
 */
package com.campustradingwall.controller;

import com.campustradingwall.dao.ProductDao;
import com.campustradingwall.model.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/product")
public class ProductDetailServlet extends HttpServlet {
    private ProductDao productDao = new ProductDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int productId = Integer.parseInt(request.getParameter("id"));
            Product product = productDao.getProductById(productId);

            if (product != null) {
                request.setAttribute("product", product);
                request.getRequestDispatcher("/product_detail.jsp").forward(request, response);
            } else {
                // 如果商品不存在，可以重定向到错误页面或首页
                response.sendRedirect(request.getContextPath() + "/");
            }
        } catch (NumberFormatException e) {
            // 如果ID格式不正确，重定向到首页
            response.sendRedirect(request.getContextPath() + "/");
        }
    }
} 